package com.charity.service.impl;

import com.charity.domain.News;
import com.charity.mapper.NewsMapper;
import com.charity.service.INewsService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Primary
public class NewsServiceImpl implements INewsService {

    @Resource
    private NewsMapper newsMapper;

    @Override
    @Transactional
    public boolean createNews(News news) {
        try {
            return newsMapper.insert(news) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateNews(News news) {
        try {
            return newsMapper.updateById(news) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteNews(Long newsId) {
        try {
            return newsMapper.deleteById(newsId) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public News getNewsById(Long newsId) {
        return newsMapper.selectById(newsId);
    }

    @Override
    public Page<News> getNewsList(String category, int pageNum, int pageSize) {
        Page<News> page = new Page<>(pageNum, pageSize);
        return newsMapper.selectList(category, page);
    }

    @Override
    @Transactional
    public boolean updateNewsStatus(Long newsId, Integer status) {
        try {
            return newsMapper.updateStatus(newsId, status) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<News> getHotNews(int limit) {
        return newsMapper.selectTopByViews(limit);
    }

    @Override
    @Transactional
    public boolean incrementViews(Long newsId) {
        try {
            return newsMapper.incrementViews(newsId) > 0;
        } catch (Exception e) {
            return false;
        }
    }
}